package com.example.liumengqiang.mvvmoneproject;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.example.liumengqiang.mvvmoneproject.mvvmutil.ActivityUtils;
import com.example.liumengqiang.mvvmoneproject.mvvmutil.ViewModelHolder;
import com.example.liumengqiang.mvvmoneproject.one.TestOneFragment;
import com.example.liumengqiang.mvvmoneproject.one.TestOneNagivator;
import com.example.liumengqiang.mvvmoneproject.one.TestOneViewModel;

public class MainActivity extends AppCompatActivity implements TestOneNagivator {

    private static final String TEST_ONE_VIEW_MODEL_TAG = "test_one_view_model_tag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取ViewModel对象
        TestOneViewModel testOneViewModel = findOrCreateViewModel();
        testOneViewModel.setNagivator(this);
        //获取Fragment对象
        TestOneFragment testOneFragment = findOrCreateViewFragment();
        testOneFragment.setViewModel(testOneViewModel);
    }

    @NonNull
    //创建Fragment
    private TestOneFragment findOrCreateViewFragment() {
        TestOneFragment tasksFragment =
                (TestOneFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
        if (tasksFragment == null) {
            // Create the fragment
            tasksFragment = TestOneFragment.newInstance();
            ActivityUtils.addFragmentToActivity(
                    getSupportFragmentManager(), tasksFragment, R.id.contentFrame);
        }
        return tasksFragment;
    }

    //创建ViewModel
    private TestOneViewModel findOrCreateViewModel() {

        @SuppressWarnings("unchecked")
        ViewModelHolder<TestOneViewModel> retainedViewModel =
                (ViewModelHolder<TestOneViewModel>) getSupportFragmentManager()
                        .findFragmentByTag(TEST_ONE_VIEW_MODEL_TAG);

        if (retainedViewModel != null && retainedViewModel.getViewmodel() != null) {
            return retainedViewModel.getViewmodel();
        } else {
            TestOneViewModel viewModel = new TestOneViewModel(getApplicationContext());
            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), ViewModelHolder.createContainer(viewModel),
                    TEST_ONE_VIEW_MODEL_TAG);
            return viewModel;
        }
    }

    @Override
    public void onClick() {
        //TODO
        Toast.makeText(this, "点我干啥？", Toast.LENGTH_SHORT).show();
    }
}
